package com.hw.one.dam2.service;

import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hw.one.core.result.MsgResult;
import com.hw.one.dam2.common.DamConstant;
import com.hw.one.dam2.dao.IPatrolTrackDao;
import com.hw.one.dam2.dao.IRegionSiteDao;
import com.hw.one.dam2.po.PatrolDataPo;
import com.hw.one.dam2.po.PatrolDevicePO;
import com.hw.one.dam2.util.CalendarUtil;
import com.hw.one.dam2.util.HttpClientUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hw.one.dam2.dao.IPatrolDeviceDao;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Service
public class PatrolDeviceService implements IPatrolDeviceService {

	@Autowired
	private IPatrolDeviceDao patrolDeviceDao;

	@Autowired
	private IPatrolTrackDao patrolTrackDao;

	@Autowired
	private IRegionSiteDao regionSiteDao;
	
	@Override
	public List<Map<String, Object>> findPatrolDeviceInfoByRegionCode(Map<String,Object> paraMap) throws Exception {
		return patrolDeviceDao.findPatrolDeviceInfoByRegionCode(paraMap);
	}

	/**
	 * 根据所属区域编码和设备类型，获取巡检设备信息
	 * 
	 * @param paraMap{regionCode:区域编码；deviceType
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Map<String,Object>> findDeviceNumByRegionCodeAndType(Map<String,Object> paraMap) throws Exception{
		
		return patrolDeviceDao.findDeviceNumByRegionCodeAndType(paraMap);
	}
	
	@Override
	public List<Map<String, Object>> findPatrolDeviceListByRegionCode(Map<String, Object> paraMap) throws Exception {

		List<Map<String, Object>> patrolDeviceList = patrolDeviceDao.findPatrolDeviceInfoByRegionCode(paraMap);
		List<String> deviceCodeList = new ArrayList<>();
		String deviceCodeS = "";
		for (Map<String, Object> patrolDevice : patrolDeviceList) {
			deviceCodeList.add((String) patrolDevice.get("deviceCode"));
			deviceCodeS += "'"+patrolDevice.get("deviceCode")+"',";
		}
		if (deviceCodeS.length() > 0) {
			deviceCodeS = deviceCodeS.substring(0, deviceCodeS.length()-1);
		}
		paraMap.put("deviceCodeS", deviceCodeS);
//		List<Map<String, Object>> tackPatrolList = SqlServerJDBC.findDeviceInfo(paraMap);
		List<Map> tackPatrolList = patrolTrackDao.findPatrolTrackRealDataByDeviceCodes(deviceCodeList);


		SimpleDateFormat sdf = new SimpleDateFormat(DamConstant.SDF_YMD_HMS);
		for (Map<String, Object> patrolDevice : patrolDeviceList) {
			boolean flag = true;
			for (Map tackPatrol : tackPatrolList) {
				if (patrolDevice.get("deviceCode").equals(tackPatrol.get("DEVICECODE"))) {
					// 设备位置信息
					String recDate = (String) tackPatrol.get("MONITORTIME");
					if (null != recDate && CalendarUtil.differentDays(new Date(), sdf.parse(recDate)) >= 0) {
						// 设备最新上传时间等于今天,认为在线
						patrolDevice.put("lat", tackPatrol.get("LATITUDE"));
						patrolDevice.put("lng", tackPatrol.get("LONGITUDE"));
						patrolDevice.put("deviceStatus", "online");
						patrolDevice.put("lastTime", recDate);
						flag = false;
						break;
					}
				}
			}
			if (flag) {
				patrolDevice.put("deviceStatus", "offline");
			}
		}
		return patrolDeviceList;
	}

	@Override
	public Map<String, Object> findPatrolDeviceTrack(Map<String, Object> paramMap) throws Exception {

		String startTime = (String) paramMap.get("startTime");
		String endTime = (String) paramMap.get("endTime");
		String deviceCode = (String) paramMap.get("deviceCode");
//		List<Map<String, Object>> trackList = SqlServerJDBC.findDeviceTrack(deviceCode, startTime, endTime);
		List<PatrolDataPo> trackList = patrolTrackDao.findPatrolTrackByDeviceCodeAndTime(paramMap);
		Collections.reverse(trackList);
		JSONArray resultList = new JSONArray();
		for (PatrolDataPo track : trackList) {
			JSONObject deviceTrack = new JSONObject();
			deviceTrack.put("deviceCode", track.getDEVICECODE());
			deviceTrack.put("monitorTime", track.getMONITORTIME());
			deviceTrack.put("lng", track.getLoc()[0]);
			deviceTrack.put("lat", track.getLoc()[1]);
			resultList.add(deviceTrack);
		}

		Map<String, Object> returnMap = new HashMap<>();
		returnMap.put("trackList", resultList);

		return returnMap;
	}

	private double[] changeGpsToBaidu(double[] loc) {
		String url = "http://api.map.baidu.com/geoconv/v1/?from=1&to=5&ak=Hqk2z8zqbtVEHi3OEwwUvUVVbTLWypWi&coords="+loc[0] + "," + loc[1];
		Map<String, String> resultMap = HttpClientUtil.sendGet(url, new HashMap<>());
		if ("200".equals(resultMap.get("statusCode"))) {
			JSONObject obj = JSONObject.parseObject(resultMap.get("result"));
			double x = obj.getJSONArray("result").getJSONObject(0).getDouble("x");
			double y = obj.getJSONArray("result").getJSONObject(0).getDouble("y");
			return new double[]{x, y};
		}else {
			return null;
		}
	}

	@Override
	public MsgResult savePatrolDeviceInfo(HttpServletRequest request) throws Exception {
		String deviceCode = request.getParameter("deviceCode");
		String carCode = request.getParameter("carCode");
		String regionName = request.getParameter("regionName");
		String companyName = request.getParameter("companyName");
		String driverName = request.getParameter("driverName");
		String phone = request.getParameter("phone");
		if (StringUtils.isEmpty(deviceCode)) {
			return MsgResult.errorResult("设备编码不能为空");
		}
		if (StringUtils.isEmpty(carCode)) {
			return MsgResult.errorResult("车牌号不能为空");
		}
		if (StringUtils.isEmpty(regionName)) {
			return MsgResult.errorResult("所属市县名称不能为空");
		}
		// 查询设备编号是否已经存在
		List<Map<String, Object>> deviceList = patrolDeviceDao.findPatrolDeviceInfoByDeviceCode(deviceCode);
		if (null != deviceList && deviceList.size() > 0) {
			return MsgResult.errorResult("设备编码已经存在");
		}
		PatrolDevicePO devicePO = new PatrolDevicePO();
		devicePO.setId(UUID.randomUUID().toString());	// 主键
		devicePO.setDeviceCode(deviceCode);		// 设备唯一标示
		devicePO.setDeviceName(carCode);	// 车牌号
		devicePO.setCarCode(carCode);	// 车牌号
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("regionName", regionName);
		List<Map<String, Object>> regionList = regionSiteDao.findRegionInfoByRegionName(paramMap);
		if (null == regionList || regionList.size() != 1) {
			devicePO.setRegionCode(regionName); // 不能模糊查询到区域
		}else {
			devicePO.setRegionCode((String) regionList.get(0).get("regionCode")); // 能模糊查询到区域
		}
		devicePO.setCompanyName(companyName);
		devicePO.setDriverName(driverName);
		devicePO.setPhone(phone);

		devicePO.setUpdateTime(new Date()); // 修改时间
		devicePO.setDeviceType(2); 	// 设备类型 1：手机；2：巡检车；3：无人机
		devicePO.setDeviceStatus("1"); 	// 设备状态 0离线；1：在线
		devicePO.setIsUse("1"); 	// 是否可用 1：可用；0：不可用
		patrolDeviceDao.insertPatrolDeviceSelective(devicePO);
		return MsgResult.okResult("保存成功");
	}

	@Override
	public MsgResult savePatrolDeviceTrackData(HttpServletRequest request) throws Exception {

		String deviceCode = request.getParameter("deviceCode");
		String longitude = request.getParameter("longitude");
		String latitude = request.getParameter("latitude");

		if (StringUtils.isEmpty(deviceCode)) {
			return MsgResult.errorResult("设备编码不能为空");
		}
		if (StringUtils.isEmpty(longitude) || StringUtils.isEmpty(latitude)) {
			return MsgResult.errorResult("经纬度不能为空");
		}
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("DEVICECODE", deviceCode);
		paramMap.put("LONGITUDE", longitude);
		paramMap.put("LATITUDE", latitude);
		SimpleDateFormat sdf = new SimpleDateFormat(DamConstant.SDF_YMD_HMS);
		paramMap.put("MONITORTIME", sdf.format(new Date()));
		patrolTrackDao.savePatrolDeviceTrackData(paramMap);
		return MsgResult.saveSuccess();
	}

	@Override
	public MsgResult findPatrolDeviceInfoByDeviceCode(HttpServletRequest request) throws Exception {
		String deviceCode = request.getParameter("deviceCode");

		if (StringUtils.isEmpty(deviceCode)) {
			return MsgResult.errorResult("设备编码不能为空");
		}
		List<Map<String, Object>> deviceInfoList = patrolDeviceDao.findPatrolDeviceInfoByDeviceCode(deviceCode);
		if (null == deviceInfoList || deviceInfoList.size() != 1) {
			return MsgResult.errorResult("查询设备信息失败,请联系管理员");
		}else {
			JSONObject obj = new JSONObject();
			obj.put("deviceCode", deviceInfoList.get(0).get("deviceCode"));
			obj.put("deviceName", deviceInfoList.get(0).get("deviceName"));
			obj.put("regionName", deviceInfoList.get(0).get("regionName"));
			return MsgResult.okResult(obj);
		}
	}

	@Override
	public MsgResult findPatrolTrackByDeviceCode(HttpServletRequest request) throws Exception {
		String deviceCode = request.getParameter("deviceCode");

		if (StringUtils.isEmpty(deviceCode)) {
			return MsgResult.errorResult("设备编码不能为空");
		}
		List<Map> deviceInfoList = patrolTrackDao.findPatrolTrackNew50ByDeviceCode(deviceCode);

		return MsgResult.okResult(deviceInfoList);

	}
}
